<template>
  <div class="container">

    <el-dialog title="音频文件上传" :visible.sync="visible" width="800px" :close-on-click-modal="false" @close="close">

      <!--      文件上传-->
      <div class="upload-file">
        <el-upload
            :action="action"
            :auto-upload="false"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-change="handleChange"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :http-request="httpRequest"
            :show-file-list="true"
            ref="upload">
          <el-button slot="trigger" size="small" type="primary">选取</el-button>
          <el-button style="margin-left: 10px;" :disabled="fileList.length < 1" size="small" type="success"
                     @click="submitUpload">上传到服务器
          </el-button>
          <div>
            <el-input
                placeholder="请输入歌手名"
                v-model="singer"
                clearable
                :disabled="fileList.length < 1">
            </el-input>
          </div>
          <div slot="tip" class="el-upload__tip">只能上传音频或者图片文件，且不超过4M，至少一张图片和一段音频</div>
        </el-upload>
      </div>

    </el-dialog>

  </div>
</template>
<script>
import {uploadMusic} from '@/request/api.js'
import axios from "axios";

export default {

  props: {
    // 由组件调用方传回的可选文件类型
    fileType: {
      type: Array,
      default: () => ["jpg", "jpeg", "png", "mp3", "mp4"],
    },
    fileSize: {
      type: Number,
      default: 4,
    },
  },
  created() {
    // this.fileList = this.list
    // 页面创建完成后拼接得到accept可选文件类型
    // this.fileType.forEach(el=>{
    //   this.accept += el
    //   this.accept += ","
    // })
    this.accept = this.fileType
    console.log(this.accept)
  },

  data() {
    return {
      visible: false,
      action: "action",
      // fileList: [],
      fileList: [],
      singer: "",
      accept: "",

    }
  },

  methods: {

    // 控制dialog的展示，由外部进行调用
    show() {
      this.visible = true
    },
    // dialog关闭后的回调
    close() {
      // 将待传文件列表清空
      this.fileList = []
      // 置dialog不显示
      this.visible = false
    },
    handleChange(file, fileList) {
      let uploadEle = this.$refs.upload

      let fileNameArr = file.name.split(".")
      if (!this.accept.includes(fileNameArr[1])) {
        this.$message.error(`文件格式不正确，请上传${this.fileType.join("/")}格式文件!`);
        // 待上传文件类型不对，返回false，阻止上传
        uploadEle.clearFiles()
        return false;
      }
      // 如果指定了最大文件大小，默认为4M
      if (this.fileSize) {
        let sizeAllow = file.size / 1024 / 1024 <= this.fileSize
        // 文件大小如果超出限制则不允许上传
        if (!sizeAllow) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          uploadEle.clearFiles()
          return false;
        }
      }

      this.fileList = fileList
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);

    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回 false 或者返回 Promise 且被 reject，则停止删除。
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    /** 手动提交上传 */
    submitUpload() {
      let uploadEle = this.$refs.upload

      if (this.fileList.length <= 0) {
        return false
      }

      const formData = new FormData()
      this.fileList.forEach((file) => {
        formData.append('file', file.raw)
      })

      if (this.singer == '' || this.singer == null) {
        formData.append('singer', localStorage.getItem("userName"))
      } else {
        formData.append('singer', this.singer)
      }


      uploadMusic(formData).then(res => {

        if (res.code == 0) {

          uploadEle.$message.success("上传成功");
          uploadEle.clearFiles()
          this.fileList = []
          this.singer = ''
        } else {
          uploadEle.$message.error("上传失败，检查后重新提交")
        }

      })

    },
    // 多文件上传时会根据文件的数量进行多次去请求
    httpRequest(param) {

      //
    }

  },

}
</script>


